<!--围栏地图 -->
<template>
  <div class="map-main">
    <!--  地图显示组件, id 必须是 map-->
    <div id="map" ref="map" class="fence-map" :style="{backgroud: '#000000'}"></div>

    <div class="mf-tool-div—top">
      <MenuToolTop @geoms-button-click="drawFenceByType"
                   @save-button-click="saveFence"
                   @cancel-button-click="cancelFence"
                   @edit-button-click="editFence"
                   @remove-button-click="removeFence"
                   @new-button-click="addFence"
                   :status="status"
                   :canEdit="canEdit"
      > </MenuToolTop>
    </div>
    <PaintTools ref="paintTools" />
  </div>
</template>
<script>
import MenuToolTop from "@/view/Home/map/site/MenuToolTop";
import PaintTools from "@/view/Home/map/maptools/tool/PaintTools";
import MapInfo from "@/view/Home/map/maptools/data/MapInfo";
import Gps from "@/view/Home/map/maptools/tool/Gps";
import MapCenterInfo from "@/api/mapinfo";
import {polygonStyle} from "@/view/Home/map/maptools/tool/style";
import LayerVector from "ol/layer/Vector";
import SourceVector from "ol/source/Vector";
import {genSource} from "@/view/Home/map/maptools/MapSource";
import {fromCircle} from "ol/geom/Polygon";
import AuthCheck from "@/api/AuthCheck";
export default {
  components:{MenuToolTop,PaintTools},
  data(){
    return{
      action:"none",//new edit,none
      addCallBack: null, //新增回调
      fenceCoordinate:null,//围栏的几何图型
      layerVector: new LayerVector(),
      mapApi: new MapCenterInfo(),
      mapObj: null,
      row:null,
      sourceVector: new SourceVector(),
      status:0, //0初始状态，1可新增，2/新增准备画图，3/新增画图结束/修改，4点击围栏（可修改），5 修改可保存
      base64FenceCoordinate: null, //Base64几何图
      canEdit:true,
    }
  },
  methods:{
    /**
     * 新回栏
     */
    addFence(status){
      //console.log(">>>>> FenceMap.addFence status=%o",status);
      //this.initData();
      this.status = 2; ////0初始状态，1可新增，2/新增准备画图，3/新增画图结束/修改，4点击围栏（可修改），5 修改可保存
      //this.action="new";
      //等待用户选择图类型
    },
    /**
     * 取消保存
     */
    afterSave(){
      if (this.status == 3){ //新增保存
        this.$refs.paintTools.clear();
        this.status=0;
      }else if (this.status == 5){ //修改保存
        this.$refs.paintTools.finishEdit();
        this.status=0;
      }

    },

    /**
     * 取消保存
     */
    afterRemove(){
      this.$refs.paintTools.clear();
      this.status=0;
    },
    /**
     * 可新增
     */
    canAdd(row){

      if (this.status == 3){
        this.$Message.error(this.$t('un_save_data_check'))//"新增围栏未保存，请先保存或取消")
        return
      }else if (this.status == 5){
        this.$Message.error(this.$t('un_save_data_check'))//"修改围栏未保存，请先保存或取消")
        return
      }

      this.row = row;
      //0初始状态，1可新增，2/新增准备画图，3/新增画图结束/修改，4点击围栏（可修改），5 修改可保存
      this.status = 1;
      this.$refs.paintTools.clear();
    },


    cancelFence(status){
      //status //0初始状态，1/新增准备画图，2/新增画图结束/修改，3点击围栏，4修改状态
      //console.log(">>>>>>>>>>FenceMap.cancelFence status=%o",status)
      if (!!this.base64FenceCoordinate){
        this.$Modal.confirm({
          title: this.$t('cancel_confirm'),
          content: this.$t('cancel_make_sure'),//'<p>确定要放弃编辑数据？</p',
          onOk: () => {
            this.$refs.paintTools.clear();
            this.status=0;
            this.base64FenceCoordinate = null;
          },
          onCancel: () => {}
        });
      }else{
        this.status=0;
        this.base64FenceCoordinate = null;
        this.action = "none";
      }
    },

    /**
     * 画围栏
     */
    drawFence(type){
      this.$refs.paintTools.clear();
      this.fenceCoordinate=null;
      this.base64FenceCoordinate = null;
      const that=this;

      //画各种图
      this.$refs.paintTools.startDraw(this.mapObj,this.sourceVector,type,(feature)=>{
        this.action="new";
        //画图完成
        //0初始状态，1可新增，2/新增准备画图，3/新增画图结束/修改，4点击围栏（可修改），5 修改可保存
        this.status=3; //画图结束
        const geometry = feature.getGeometry();
        //取得圈顶点的值
        let coordinate = []
        if (geometry.getType() == "Circle"){
          //园转为几何图形
          const polygon = fromCircle(geometry)
          //几何图形才能取得 定位点
          coordinate = polygon.getCoordinates();
        }else{
          coordinate = geometry.getCoordinates();
        }
        that.fenceCoordinate=coordinate;
        //删除原型属性，再转为Basement4
        Object.setPrototypeOf(coordinate,null);
        console.log("coordinate=%o",coordinate);
        //再转Base64
        let base64Str = btoa(JSON.stringify(coordinate));
        console.log("base64Str=%o",base64Str);
        this.base64FenceCoordinate = base64Str;

/*
        //BASE64 --> 再转回 JSON
        let destGeoJson = atob(base64Str)
        console.log("destJson=%o",destGeoJson);
        let destObject = JSON.parse(destGeoJson);
        console.log("destObject=%o",destObject);
*/
      });
    },
    /**
     * 围栏按钮的点击 事件处理
     * @param type
     */
    drawFenceByType(type){
      this.drawFence(type);
    },
    /**
     * 修改围栏
     * @param base64Coordinate
     */
    editFence(status){
      //console.log(">>>>>>>> FenceMap.editFence() status=%o",status);
      if (!this.row){
        return;
      }
      this.action="edit";

      //this.row = row;
      this.base64FenceCoordinate = this.row.coordinate;
      this.fenceCoordinate=null;
      //BASE64 --> 再转回 JSON
      let destGeoJson = atob(this.row.coordinate)
      let destObject = JSON.parse(destGeoJson);
      this.$refs.paintTools.editPolygon(this.mapObj,this.sourceVector,destObject);
      this.status=5; //0初始状态，1可新增，2/新增准备画图，3/新增画图结束/修改，4点击围栏（可修改），5 修改可保存
    },

    /**
      取得修改后的数据
     */
    getEditPolygonCoordinate(){
      return this.$refs.paintTools.getEditPolygonCoordinate();
    },

    init() {
      /** 生成画图的图层和资源 */
      this.layerVector.setStyle(polygonStyle); //自定义的地图风格
      this.layerVector.setSource(this.sourceVector);
      if (!!this.mapObj){
        //鼠标移动事件
        if (!!this.mapEventFun.pointermoveEvent){
          this.mapObj.un("pointermove",this.mapEventFun.pointermoveEvent);
        }
        //地图放大事件
        if (!!this.mapEventFun.mapZoomEvent){
          this.mapEventFun.mapZoom.removeZoomRegister();
        }
      }

      //产生新的地图

      this.mapObj = genSource("map", this.mapObj, this.mapInfo);
      this.mapObj.getView().setZoom(14);

      const that = this;
      this.$nextTick(()=>{
        if (!that.mapObj){
          that.$Message.error("地图服务器的原因，地图加载失败！");
          return;
        }
        //给地图强化，加事件，弹窗等
        this.genMapEventFuns();
      });
      if (!!this.mapObj){
        this.mapObj.addLayer(this.layerVector);
      }
      this.emitMapInfo();
      //传递地图至上级
      this.$emit('after-gen-map', this.mapObj);
    },

    /**
     * 给地图增加各种事件
     */
    genMapEventFuns(){
      ;
    },
    /**
     * 传递地图信息
     */
    emitMapInfo(){
      let level=!!this.currentLevel?this.currentLevel.toFixed(1):0;
      const event = "《" + this.currentMapSource + " " + this.currentMapType +"》，级别：" + level;
      this.$emit('map-info-event', event);
    },

    /**
     * 重画围栏
     *
     */

    redrawFence(row){
      if (this.status == 3){
        this.$Message.error(this.$t('un_save_data_check'))//"新增围栏未保存，请先保存或取消")
        return
      }else if (this.status == 5){
        this.$Message.error(this.$t('un_save_data_check'))//"修改围栏未保存，请先保存或取消")
        return
      }

      this.row = row;
      //BASE64 --> 再转回 JSON
      let destGeoJson = atob(row.coordinate)
      //console.log("destJson=%o",destGeoJson);
      let destObject = JSON.parse(destGeoJson);
      //console.log("destObject=%o",destObject);
      this.$refs.paintTools.reDrawPolygon(this.mapObj,this.sourceVector,destObject);
      this.status=4;//点击周围
    },
    /**
     * 屏新地图
     */
    refreshMap(){
      //刷新地图尺寸
      this.$nextTick(() => {
        if (!!this.mapObj ){
          this.mapObj.updateSize();
        }
      })
    },

    removeFence(){
      this.$emit("remove-fence",this.row)
    },

    /**
     * 通知是否保存结果
     * @param saveResult  1成功,-1失败, 0取消
     */
/*    resultNotify(saveResult){
      if (saveResult == 1 || saveResult == 0){
        this.status = 0;
      }
    },*/


/*    setStatus(row,status){
      //0初始状态，1可新增，2/新增准备画图，3/新增画图结束/修改，4点击围栏（可修改），5 修改可保存
      this.row = row;
      this.status = status;
    },*/
    /**
     * 保存
     */
    saveFence(){
      //console.log(">>>>>>>> FenceMap.saveFence() status=%o",this.status);
      if (this.status == 3){//新增保存
        if (!this.base64FenceCoordinate){
          this.$Message.error(this.$t('none_data_to_save'))//"请先画好围栏再保存！");
          return;
        }
        this.$emit("save-of-new",this.row,this.base64FenceCoordinate)
      }else if (this.status == 5) {//修改保存
        //console.log(">>>>>>>> FenceMap.saveFence() status=%o",this.status);
        this.$emit("save-of-edit",this.row,this.getEditPolygonCoordinate())
      }
    },
  },
  mounted() {
    /** 取得默认的地图信息 */
    //从后台地图中心点
    const that = this;
    this.$nextTick(()=>{
      that.mapInfo = new MapInfo().get();
      that.init();
      console.log(">>>>>> FenceMap.mounted(): canEdit=%o",new AuthCheck().fenceMaintainEdit());
      this.canEdit = new AuthCheck().fenceMaintainEdit();
    })
  }
}


</script>
<style lang="less">
.map-main{
  width: 100%;
  height: 100%;
}
.fence-map {
  width: 100%;
  height: 100%;
  margin: 0;
}
//顶边工具栏
.mf-tool-div—top {
  top: 200px;
  height: 32px;
  //position: absolute;
  position: fixed;
  right: 20px;
  //left:240px;
  z-index: 999;
  //border-color: #e30c0c transparent transparent transparent;
  //background-color: rgb(25, 131, 239);
}
</style>
